using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;


public interface ICustomSceneEditor
{
    void Show(GameObject go);

    void OnGUI(GameObject go);

    void Hide();
}

public class EditorSceneGUICustom<Editor, Component> : ICustomSceneEditor
     where Editor : ICustomSceneEditor, new()
     where Component : UnityEngine.Component
{
    static int instanceID;
    static Editor editor;

    public static void InitGUI()
    {
        GameObjectOverrideInspector.GUIHander.Add(OnCustomGUI);
    }


    public static void OnCustomGUI(GameObject go)
    {
        if (instanceID != go.transform.GetInstanceID())
        {
            if (go.GetComponent<Component>())
            {
                try
                {
                    editor?.Hide();
                }
                catch
                { }

                instanceID = go.transform.GetInstanceID();
                editor = new Editor();
                editor.Show(go);
            }
            else
            {
                if (instanceID != 0)
                {
                    if (IsChild(go.transform, instanceID) == false)
                    {
                        Close();
                    }
                }
            }
        }
        else
        {
            editor?.OnGUI(go);
        }
    }

    public static bool IsChild(Transform go, int instanceID)
    {
        if (go.GetInstanceID() == instanceID)
            return true;

        if (go.transform.parent == null)
            return false;

        return IsChild(go.transform.parent, instanceID);
    }


    public static void Close()
    {
        instanceID = 0;
        editor?.Hide();
        editor = default;

    }


    public virtual void Show(GameObject go) { }

    public virtual void OnGUI(GameObject go) { }

    public virtual void Hide() { }

}




